package com.star.mall.aspect;

import com.star.mall.base.helper.CommonRedisLockHelper;
import com.star.mall.base.model.Lock;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;

@Aspect
@Component
@Slf4j
public class RedisAspect {

    @Resource
    CommonRedisLockHelper redisLockHelper;

    @Around("@annotation(lock)")
    public Object execute(ProceedingJoinPoint point, Lock lock) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        Lock annotation = method.getAnnotation(Lock.class);
        String key = annotation.key();

        redisLockHelper.execute(key, a -> {
            try {
                point.proceed();
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        });
        return null;
    }
}
